<template>
    <div id="editormdid">
        <textarea v-model="content" style="display:none;"></textarea>
    </div>
</template>

<script>
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
    setup() {

    },
    name: 'Editor',
    data() {
        return {
            instance: null,
            content: '',
            filename: this.$route.params.name          //'this.$route.params.name'
        };
    },
    props: {
      initTreeDatas: {
        type: Function,
        default: null
      }
    },
    mounted() {
        this.initEditor();
        this.content = '';
        this.getFileContent();
    },
    beforeDestroy(){
        let post_data = {'filename': this.filename}
        this.$api.doc.exitEdit(post_data).then(res=>{
            console.log('exitEdit ok!')
            console.log(res)
        })
    },
    methods: {
        getFileContent: function(){
            console.log(this.filename)
            let get_data = {'filename': this.filename}
            this.$api.doc.getContent(get_data).then(res=>{
                console.log('res contenet')
                this.content = res.data.data
            })
        },
        initEditor() {
            let _this = this;
            this.instance = window.editormd("editormdid", {
                height: '870px',
                emoji: true,
                path: 'editormd/lib/',
                previewing: true,
                // 上传图片
                // imageUpload : true,
                // imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp", "txt"],
                // imageUploadURL : "/api/markdown/uploadImage/", //注意你后端的上传图片服务地址
                toolbarIcons: function () {  //自定义工具栏，后面有详细介绍
                    return [
                        "undo", "redo", "|",
                        "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
                        "h1", "h2", "h3", "h4", "h5", "h6", "|",
                        "list-ul", "list-ol", "hr", "|",
                        "link", "reference-link", "imageUpload", "code", "preformatted-text", "code-block", "table",
                        "datetime", "emoji", "html-entities", "pagebreak", "|",
                        "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|", "help", "info",
                        "|", "savebutton", 
                    ]; // full, simple, mini
                },
                toolbarIconTexts: {
                    savebutton: '保存',
                    imageUpload: '图片上传'
                },
                // 用于增加自定义工具栏的功能，可以直接插入HTML标签，不使用默认的元素创建图标
                // toolbarCustomIcons : {
                //     // savebutton : '<button id="savebutto_md" click="SaveFile()" style="background-color: rgb(228, 235, 229);margin-left: 20px;padding: 4px;border-radius:10px;"><h4>Save</h4></button>'
                // },
                toolbarIconsClass: {
                  downButton: 'fa-download',
                  savebutton: 'fa-save',
                  imageUpload: 'fa-upload'
                },
                lang: {
                    toolbar: {
                      downButton: '下载Markdown文档',
                      savebutton: '保存md文件内容',
                      imageUpload: '上传图片/附件'
                    }
                },
                onload: function() {
                    _this.initPasteDragImg(_this.instance)
                },
                toolbarHandlers: {
                    imageUpload: function() {
                        alert('可直接粘贴或拖拽图片到编辑器内！')
                    },
                    savebutton: function (){
                        const cur_file = _this.filename
                        const res_content = this.getMarkdown()
                        let post_data = {'filename': cur_file, 'content': res_content}
                        _this.$api.doc.updateContent(post_data).then(res=>{
                        alert(res.data.message)
                        if(res.data.code===3){
                            _this.$emit("fathre")
                        }
                        })
                    },
                    downButton: function(){
                        console.log("downButton")
                        let post_data = {'filename': _this.filename}
                        _this.$api.doc.getFilePath(post_data).then(res=>{
                            console.log(res)
                            let get_data = {'filename': res.data.filepath}
                            _this.$api.doc.downLoadFile(get_data)
                        })
                    }
                }
            });
        },
        initPasteDragImg(Editor){
            let that = this;
            let doc = document.getElementById(Editor.id)
            doc.addEventListener('paste', function (event) {
                let items = (event.clipboardData || window.clipboardData).items;
                let file = null;
                if (items && items.length) {
                    // 搜索剪切板items
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].type.indexOf('image') !== -1) {
                            file = items[i].getAsFile();
                            break;
                        }
                    }
                } else {
                    console.log("当前浏览器不支持");
                    return;
                }
                if (!file) {
                    console.log("粘贴内容非图片");
                    return;
                }
                console.log(file)
                that.uploadImg(file, Editor)
            });
            let dashboard = document.getElementById(Editor.id)
            dashboard.addEventListener("dragover", function (e) {
                e.preventDefault()
                e.stopPropagation()
            })
            dashboard.addEventListener("dragenter", function (e) {
                e.preventDefault()
                e.stopPropagation()
            })
            dashboard.addEventListener("drop", function (e) {
                e.preventDefault()
                e.stopPropagation()
                let files = this.files || e.dataTransfer.files;
                console.log(files)
                that.uploadImg(files[0], Editor)
             })
        },
        uploadImg(file,Editor){
            let formData = new FormData();
            formData.append('file', file, file.name);
            formData.append('filename', this.filename);
            this.$api.doc.uploadImage(formData).then(res=>{
              console.log(res)
              Editor.insertValue(res.data.link)
            })
        }
    },
})
</script>

<style scoped>
/* @import url('../pluguns/editormd/css/editormd.css') */
#savebutto_md {
    background-color: rgb(228, 235, 229);
    margin-left: 20px;
    
}
</style>
